/* AT25DF SPI Flash driver */

/* Copyright (C) 2011 David Zanetti
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <avr/io.h>
#include <avr/pgmspace.h>
#include <stdio.h>
#include <avr/eeprom.h>
#include "global.h"
#include <util/delay.h>
#include "at25df.h"
#include "spi.h"
#include "serial.h"

/* where is our CS pin? */
#define CSDDR DDRC
#define CSPORT PORTC
#define CS PORTC1

#define SPI_START CSPORT &= ~(1 << CS);
#define SPI_END CSPORT |= (1 << CS);

uint8_t at25df_good;

/* init the chip, and validate it's identified properly */
void at25df_init(void) {
	uint8_t manu, devid1, devid2, ext;

	/* set the init flag to good, and we'll set any failures to 0 */
	at25df_good = 1;

	/* init hardware SPI port */
	spi_init();

	/* set DDR for our CS pin */
	CSDDR |= (1 << CS);

	/* send request for device IDs */
	SPI_START;
	spi_txrx(0x9f);
	/* and read result */
	manu = spi_txrx(0);
	devid1 = spi_txrx(0);
	devid2 = spi_txrx(0);
	ext = spi_txrx(0);
	SPI_END;

	/* report what we get back, we're expecting values as in
    table 11-2, pg27 */

	switch (manu) {
		case 0x1f:
			/* ATMEL */
			serial0_tx_PGM(PSTR("at25df: found Atmel "));
			break;
		default:
			/* unknown */
			serial0_tx_PGM(PSTR("at25df: unknown chip or no response\r\n"));
			at25df_good = 0;
			break;
	}

	if (!at25df_good) {
		return;
	}

	switch (devid1) {
		case 0x44:
			serial0_tx_PGM(PSTR("AT25/26DFxxx 4-Mbit\r\n"));
			break;
		default:
			serial0_tx_PGM(PSTR("unknown\r\n"));
			at25df_good = 0;
			break;
	}

	return;
}


